#include "comm.hpp"

int main()
{
    // 1.创建key
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("cerate key done", Debug) << " client key : " << k << endl;

    // 2.获取共享内存
    int shmid = shmget(k, SHM_SIZE, 0);
    if (shmid == -1)
    {
        perror("shmget");
        exit(1);
    }
    Log("cerate shm done", Debug) << " shmid : " << shmid << endl;

    // 3.将共享内存,挂接到指定的地址空间
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == nullptr)
    {
        Log("attach shm fail", Debug) << " shmid : " << shmid << endl;
        exit(1);
    }

    Log("attach shm done", Debug) << " shmid : " << shmid << endl;
    sleep(10);

    // 进行通信
    int fd = OpenFIFO(FIFO_NAME, WRITE); // 用管道实现共享内存的同步(达到访问控制的效果)

    // 从键盘读取数据
    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0)
        {
            shmaddr[s - 1] = 0;
            Signal(fd);
            if (strcmp(shmaddr, "quit") == 0)break;
        }
    }

    CloseFifo(fd);
    // char a = 'a';
    // for(;a<'z';a++)
    // {
    //     snprintf(shmaddr,SHM_SIZE-1,"hello server, 我是其它进程,我的pid: %d, inc:%d\n",getpid(),a);
    //     sleep(2);
    // }

    strcpy(shmaddr, "quit");

    // 4.将共享内存,从自己的地址空间去关联
    int n = shmdt(shmaddr);
    assert(n != -1);

    return 0;
}

